package top.shmly.universal.web.rest;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.shmly.universal.base.common.Result;
import top.shmly.universal.base.common.SysUser;
import top.shmly.universal.base.response.ResponseCode;
import top.shmly.universal.base.response.ResponseResult;
import top.shmly.universal.utils.impl.JwtUtilsImpl;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @program: universal
 * @description: login
 * @author: Jibny
 * @date 2021-04-27 12:07:36
 */
@Api(tags = "登录")
@RestController
public class LoginController {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @ApiOperation(value = "登录获取token", notes = "登录获取token")
    @PostMapping("/login")
    public Result<String> login(@RequestBody SysUser sysUser, HttpServletRequest request){

        final UserDetails userDetails = userDetailsService.loadUserByUsername(sysUser.getUsername());
        final String token = "Bearer "+JwtUtilsImpl.getInstance().generateToken(userDetails);
        return new ResponseResult<String>().ok(ResponseCode.CODE_200,token);
    }

    @ApiOperation(value = "haha", notes = "haha")
    @PostMapping("haha")
    public String haha(){
        UserDetails userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return "haha:"+userDetails.getUsername()+","+userDetails.getPassword();
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        String key = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD";
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), "0102030405060708".getBytes());

        String secret="h2aHqg6e0LZcl3bPsEdUsloXAT5+vnInRSrC+u2S/4tZ2RWl1zMWmCLrV4WooTW03kgsL6dwlEe+TY8SNSRVK7gwlwfsYobnvdMeiG7WjAA=}";

        byte[] asBytes = Base64.getDecoder().decode(secret);
        System.out.println(new String(asBytes, "utf-8"));

    }
}
